﻿using UnityEngine;
using System.Collections;

public class MusicComponent : MonoBehaviour
{
    //--------------断点下载变量--------------------
    /// <summary>
    /// 此参数必须为网络地址
    /// </summary>
    public string MusicWebUrl = "http://down.5nd.com/a/down.ashx?t=1&xcode=183941edb81ab13a9ac500805bc026dc&sid=603532";
    /// <summary>
    /// 缓存的本地相对地址
    /// </summary>
    public string LocalCache = @"1.mp3";
    long MusicLength;
    /// <summary>
    /// 资源实际总长度
    /// </summary>
    public int musicAllLength
    {
        get { return (int)MusicLength; }
    }
    int YetDownload;
    /// <summary>
    /// 已经下载的长度
    /// </summary>
    public int musicYetDownload
    {
        get { return YetDownload; }
    }
    /// <summary>
    /// 是否正在播放
    /// </summary>
    bool IsPlay = false;
    /// <summary>
    /// 是否下载
    /// </summary>
    bool IsDown = false;
    bool isDown
    {
        get
        {
            if (IsDown == true)
            {
                IsDown = false;
                isDownTick_true = false;
                return true;
            }
            return false;
        }
    }
    //-----------------委托变量--------------------
    System.Action<bool> isDownTick;
    //委托是否开启
    bool isDownTick_true = false;
    //-----------------播放变量----------------------
    //音频组件
    AudioSource[] arrAllAudioSource;
    AudioSource AudioSourceing = null;
    bool musicIsplay = false;
    int musicUpLength = 0;

    //---------------------------------------------
    //播放
    public void Play(System.Action<bool> isDownTick_)
    {
        StopCoroutine("StreamingDownload");
        //初始化委托
        isDownTick = isDownTick_;
        //初始化变量
        musicUpLength = 0;
        IsDown = false;
        IsPlay = true;
        if (MusicWebUrl == "" || LocalCache == "")
        {
            Debug.Log("MusicWebUrl 或 LocalCache 为空！");
            return;
        }
        //检测this是否有音频组件 没有则创建

        musicIsplay = true;
        isDownTick_true = true;

        //调用下载
        StartCoroutine(StreamingDownload(MusicWebUrl, Application.persistentDataPath + "/" + LocalCache));

    }
    //停止
    public void Stop()
    {
        AudioSourceing.Stop();
        //初始化委托
        isDownTick_true = false;
        isDownTick = null;
        IsPlay = false;
        AudioSourceing = null;

        musicIsplay = false;
        isDownTick_true = false;
        StopCoroutine("StreamingDownload");

    }
    void Update()
    {
        if (IsPlay && isDownTick_true)
        {
            bool isdown_ = isDown;
            if (musicIsplay == true && isdown_)
            {
                StartCoroutine(MusicMain());
            }
            else if ((musicYetDownload / 1024) > 300 && musicUpLength == 0)
            {
                musicUpLength = musicYetDownload;
                StartCoroutine(MusicMain());
                Debug.Log("1");
            }
            //else if ((musicUpLength / 1024) + 500 < (musicYetDownload / 1024))
            //{
            //    musicUpLength = musicYetDownload;
            //    StartCoroutine(setC());
            //    Debug.Log("2");
            //}


            //调用信息回调委托
            isDownTick(isdown_);
        }
        if (AudioSourceing != null)
        {
            if (AudioSourceing.isPlaying)
            {
                if (((float)(AudioSourceing.timeSamples) / (float)(AudioSourceing.clip.samples)) > 0.7f && isDown == false)
                {
                    StartCoroutine(MusicMain());
                }
                Debug.Log(AudioSourceing.timeSamples + "  " + AudioSourceing.clip.samples);

            }
        }


    }
    /// <summary>
    /// 断点下载
    /// </summary>
    /// <param name="MusicWebUrl"></param>
    /// <param name="LocalCache"></param>
    /// <returns></returns>
    IEnumerator StreamingDownload(string MusicWebUrl, string LocalCache)
    {

        //打开网络连接 
        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(MusicWebUrl);
        System.Net.HttpWebRequest requestGetCount = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(MusicWebUrl);
        //获取资源长度
        long countLength = requestGetCount.GetResponse().ContentLength;
        MusicLength = countLength;
        //打开上次下载的文件或新建文件 
        long lStartPos = 0;
        System.IO.FileStream fs;
        //检测是否有文件
        if (System.IO.File.Exists(LocalCache))
        {
            fs = System.IO.File.OpenWrite(LocalCache);
            lStartPos = fs.Length;
            YetDownload = (int)lStartPos;
            //判断是否下载完成
            if (countLength - lStartPos <= 0)
            {
                IsDown = true;
                fs.Close();
                yield break;
            }
            fs.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针 
        }
        else
        {
            //创建文件
            fs = new System.IO.FileStream(LocalCache, System.IO.FileMode.Create);
        }
        //设置Range值  进行断点下载
        if (lStartPos > 0)
        {
            request.AddRange((int)lStartPos);
        }
        //向服务器请求，获得服务器回应数据流 
        System.IO.Stream ns = request.GetResponse().GetResponseStream();
        int len = 1024 * 8; //音频 8的倍数
        byte[] nbytes = new byte[len]; //创建byte数组
        int nReadSize = 0;
        nReadSize = ns.Read(nbytes, 0, len);
        //循环读取数据
        while (nReadSize > 0)
        {
            fs.Write(nbytes, 0, nReadSize);
            nReadSize = ns.Read(nbytes, 0, len);
            YetDownload = (int)fs.Length;
            //t = "已下载:" + fs.Length / 1024 + "kb /" + countLength / 1024 + "kb";
            yield return false;
        }
        IsDown = true;
        ns.Close();
        fs.Close();
    }

    IEnumerator MusicMain()
    {
        WWW www = new WWW("file:///" + Application.persistentDataPath + "/" + LocalCache);
        yield return www;
        AudioClip chuancun = www.GetAudioClip(true, true, AudioType.MPEG);

        this.gameObject.AddComponent<AudioSource>();
        arrAllAudioSource = this.gameObject.GetComponents<AudioSource>();

        if (arrAllAudioSource.Length >= 2)
        {

            arrAllAudioSource[arrAllAudioSource.Length - 1].clip = chuancun;
            arrAllAudioSource[arrAllAudioSource.Length - 1].timeSamples = arrAllAudioSource[arrAllAudioSource.Length - 2].timeSamples;
            arrAllAudioSource[arrAllAudioSource.Length - 1].Play();
            AudioSourceing = arrAllAudioSource[arrAllAudioSource.Length - 1];
            for (int i = 0; i < arrAllAudioSource.Length - 1; i++)
            {
                Destroy(arrAllAudioSource[i]);
            }
            //Destroy(arrAllAudioSource[0]);
        }
        else if (arrAllAudioSource.Length == 1)
        {
            arrAllAudioSource[0].clip = chuancun;
            arrAllAudioSource[0].Play();
            AudioSourceing = arrAllAudioSource[0];

        }
    }

}
